package com.tt.fashionWebSite.util;

import org.ini4j.Profile;
import org.ini4j.Wini;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * Created by isoft-work 5 on 12/30/2014.
 */
public class UploadFile {
   public String saveImage(MultipartFile files) {
      try {
         // get project path
         String imageSrcPath = "";
         String pathSettingFile = ISSConstants.webappDir.getCanonicalPath() + "/setting.ini";
         File settingFile = new File(pathSettingFile);;
         Wini ini = new Wini(settingFile);
         Profile.Section sec = ini.get("UploadPath");
         if (sec != null && sec.containsKey("projectDir")) {
            imageSrcPath = sec.get("projectDir");
         }
         // save file
         byte[] bytes = files.getBytes();
         Date now = new Date();
         String fileName = now.getTime() + files.getOriginalFilename();
         // Creating the directory to store file
//         String rootPath = System.getProperty("user.dir");
         imageSrcPath = imageSrcPath + ISSConstants.imageTargetDir;
         String imageTarget = ISSConstants.imageTargetDir;
         File dir = new File(imageSrcPath);
         if (!dir.exists()) {
            dir.mkdirs();
         }

         // Create the file on server
         File serverFile = new File(dir.getAbsolutePath()
               + File.separator + fileName);
         BufferedOutputStream stream = new BufferedOutputStream(
               new FileOutputStream(serverFile));
         stream.write(bytes);
         stream.close();
         return imageTarget + fileName;
      }
      catch (Exception ex) {
         System.out.print(ex);
         return "";
      }
   }
}
